<?php
namespace User\Controller;
use Think\Controller;

/**
 * @Author: Martin Zhou
 * @Version: 1.0.1
 * @Copyright Tencent Security Response Center (TSRC)
 * @Project  https://security.tencent.com/index.php/xsrc
*/


class LoginController extends Controller {
    /**
    登陆页面
    **/
    public function index(){
		$tmodel= M('setting');
		$title = $tmodel->where('id=1')->select(); 
		$setting = M('setting')->where(array('name'=>'site_register_setting'))->find();
		$this->assign('title', $title);
		$this->assign('setting',$setting['value']);
        $this->display();
    }
	
    /**
    登陆验证
    **/
    public function login(){
        if(!IS_POST){$this->error("非法请求");}
        $member = M('member'); 
        $rawData = file_get_contents("php://input"); 
        // 解码 JSON 数据
        $data = json_decode($rawData, true); // 第二个参数为 true 返回数组，若为 false 则返回对象
        $password =  $data['password']; 
        $code = $data['verify']; 
        $email =  $data['username']; 
        
        $agreeProtocol =  $data['agreeProtocol']; 
        if($agreeProtocol == false){
            $result = ['code' => '400', 'msg' => '请阅读并同意遵守GSRC安全测试及漏洞提交规范', 'url' =>U('Login/index') ];
            $this->ajaxReturn($result,'JSON'); 
        } 
		if(!($this->check_verify($code,'login'))){
		   session('userId',null);
		   session('username',null);
		   $result = ['code' => '400', 'msg' => '验证码错误', 'url' =>U('Login/index') ];
		   $this->ajaxReturn($result,'JSON'); 
           //$this->error('验证码错误',U('Login/index'));
        }
		
        $user = $member->where("email = '$email' OR username = '$email'")->find();

		if($user['password'] != md5(md5(md5($user['salt']).md5($password)."SR")."CMS")) {
		   //$this->error('账户或密码错误',U('Login/index'));
		   $result = ['code' => '400', 'msg' => '账户或密码错误', 'url' =>U('Login/index') ];
		   $this->ajaxReturn($result,'JSON'); 
        }
		
        if($user['status'] == 0){
            //$this->error('账号被删除或禁用，请联系管理员 :(') ;
            $result = ['code' => '400', 'msg' => '账号被删除或禁用，请联系管理员', 'url' =>U('Login/index') ];
            $this->ajaxReturn($result,'JSON'); 
        }
		$token = md5(md5($user['email'].time()).time());
        //更新登陆信息
        $data =array(
            'id' => $user['id'],
            'update_at' => time(),
            'login_ip' => $this->new_get_client_ip(),
			'token' => $token 
            //2017-07-02 fix bug: token can't be inserted into databease. By. yuyang
        );
        //登陆成功
		$message_num = M('message') -> where(array('userid'=>$user['id'],'read'=>0)) -> count();
		
        if($member->save($data)){
		    /**session('token',$token);
            $this->success("请先完成验证",U('Login/svalid?email=').$user['email']);
			**/
			session('token',$token);
			session('userId',$user['id']);
            session('username',$user['username']);
			session('avatar',$user['avatar']);
			session('mnum',$message_num);
			//redirect('./index.php');
			$result = ['code' => '200', 'msg' => '登录成功', 'url' =>U('Index/index') ];
			$this->ajaxReturn($result,'JSON'); 
        }   

    }
    /**
     * 协议页面
     */
    public function security(){
        $this->display();
    }
	//验证码
    public function verify($tab, $key){  
		ob_clean();
        $Verify = new \Think\Verify();
        $Verify->codeSet = '123456789abcdefg';
        $Verify->fontSize = 16;
        $Verify->length = 4;
        $Verify->entry($tab);
    }
	
    protected function check_verify($code, $tab){
        $verify = new \Think\Verify();
        return $verify->check($code, $tab);
    }

	
    //退出登录
    public function logout(){
        session('userId',null);
        session('username',null);
		session('avatar',null);
		session('mnum',null);
        redirect(U('Login/index'));
    }
    
    
    
    /**
     * 您可以通过检查这些头信息来获取真实的 IP 地址。
     * @return string|unknown
     */
    function new_get_client_ip() {
        $ip = '';
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // X-Forwarded-For 可能包含多个 IP，用逗号分隔，取第一个非私有 IP
            $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($ips as $item) {
                $item = trim($item);
                if (filter_var($item, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $item; // 返回第一个有效的非私有 IP
                }
            }
        }
        
        // 如果没有找到有效的 X-Forwarded-For，则使用 REMOTE_ADDR
        if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
            return $_SERVER['HTTP_X_REAL_IP'];
        } else {
            return $_SERVER['REMOTE_ADDR']; // 最后退回到 REMOTE_ADDR
        }
    }
}